package com.example.x6.serial;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

public class Uart {

  private SerialPort serialdayin;
  private InputStream dayinInputStream;
  private OutputStream dayinOutputStream;

  public  SerialPort serialQR;
  public  InputStream QRInputStream;
  public  OutputStream QROutputStream;

  public  SerialPort serialMCU;
  public  InputStream MCUInputStream;
  public  OutputStream MCUOutputStream;
  /* 打开打印机串口 */
  public void init_dayin_serial() {
    try {
      serialdayin = new SerialPort(new File("/dev/ttyS7"),9600,0);
      dayinInputStream = serialdayin.getInputStream();
      dayinOutputStream = serialdayin.getOutputStream();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  /* 打开QR串口 */
  public void init_QR_serial() {
    try {
      serialQR = new SerialPort(new File("/dev/ttyS4"),9600,0);
      QRInputStream = serialQR.getInputStream();
      QROutputStream = serialQR.getOutputStream();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  /* 打开MCU串口 */
  public void init_MCU_serial() {
    try {
      serialMCU = new SerialPort(new File("/dev/ttyS2"),115200,0);
      MCUInputStream = serialMCU.getInputStream();
      MCUOutputStream = serialMCU.getOutputStream();
    } catch (IOException e) {

      e.printStackTrace();
    }
  }


  /**
   * 串口打印机发送
   */
  public void Uart_dayin_Send( String str) throws UnsupportedEncodingException {
    byte[] bs = str.getBytes("GB2312");
    try {
      dayinOutputStream.write(bs);
    }   catch (IOException e) {
    }
  }
  /**
   * 串口打印机打印二维码
   */

  public void Uart_dayin_QR( String str) throws UnsupportedEncodingException {
    byte[] A = str.getBytes("GB2312");
    byte[] B = new byte[]{0x1D, 0x4D, 0x01};// 读取通道值
    byte[] D = new byte[]{0x00};// 读取通道值
    byte[] C = byteMerger(B, A);
    byte[] E = byteMerger(C, D);

    try {
      dayinOutputStream.write(E);
    } catch (IOException e) {
    }
  }
  //System.arraycopy()方法
  public static byte[] byteMerger(byte[] bt1, byte[] bt2) {
    byte[] bt3 = new byte[bt1.length + bt2.length];
    System.arraycopy(bt1, 0, bt3, 0, bt1.length);
    System.arraycopy(bt2, 0, bt3, bt1.length, bt2.length);
    return bt3;
  }

  /**
   * 串口打印机发送
   */
  public void Uart_MCU_Send( String str) throws UnsupportedEncodingException {
    byte[] bs = str.getBytes("GB2312");
    try {
      MCUOutputStream.write(bs);
    }   catch (IOException e) {
    }
  }


  /**
   * 串口发送
   */
  //   01 06 00 02 00 01 e9 ca
  //  byte[] A= new byte[]{0x01,0x06,0x00,0x02,0x00,0x01,0xe9,0xca};
  //Uart_Send(A)
  public void Uart_Send(byte []byte1)throws UnsupportedEncodingException {
    try {
      MCUOutputStream.write(byte1);
    } catch (IOException e) {
    }
  }
}
